﻿using System;
using System.Collections.Generic;
using System.Text;
using Tamir.SharpSsh;

namespace SharpSSH.Standard
{
    public class ShellHelp
    {
        SshExec exec = null;
        bool IsLoginSuccess = false;

        /// <summary>  
        /// 打开连接  
        /// </summary>  
        /// <param name="host"></param>  
        /// <param name="username"></param>  
        /// <param name="pwd"></param>  
        /// <returns></returns>  
        public (bool, string) OpenShell(string host, string username, string pwd)
        {
            string msg = "";
            try
            {
                exec = new SshExec(host, username, pwd);
                //XXLog.Log(String.Format("[{0}]Connecting...", host));
                exec.Connect();
                IsLoginSuccess = exec.Connected;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return (IsLoginSuccess, msg);
        }
        /// <summary>  
        /// 重新打开连接  
        /// </summary>  
        /// <param name="host"></param>  
        /// <param name="username"></param>  
        /// <param name="pwd"></param>  
        /// <returns></returns>  
        public (bool, string) AgainOpenShell()
        {
            string msg = "";
            try
            {
                //XXLog.Log(String.Format("[{0}]Connecting...", host));
                exec.Connect();
                IsLoginSuccess = exec.Connected;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return (IsLoginSuccess, msg);
        }
        /// <summary>  
        /// 执行命令  
        /// </summary>  
        /// <param name="cmd"></param>  
        public string Shell(string cmd)
        {
            if (string.IsNullOrEmpty(cmd))
            {
                throw new ArgumentNullException(cmd);
            }
            if (!IsLoginSuccess)
            {
                throw new Exception("未登录授权");
            }
            return exec.RunCommand(cmd);
        }
        /// <summary>  
        /// 关闭连接  
        /// </summary>  
        public void Close()
        {
            if (exec != null) exec.Close();
        }
        /// <summary>  
        /// 获取连接状态  
        /// </summary>  
        public bool GetState()
        {
            return exec != null ? exec.Connected : false;
        }

    }
}
